package com.libre.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.libre.auth.entity.Role;
import com.libre.auth.entity.User;
import com.libre.auth.mapper.RoleMapper;
import com.libre.auth.service.UserService;
import com.libre.common.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 实现UserDetailsService接口
 * 使用@Component把它注册为组件，便于spring进行实例化
 */
@Component
public class SecurityUserService implements UserDetailsService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserService userService;

    //根据用户名查询用户信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (!StringUtil.isNotEmpty(username)) {
            throw new UsernameNotFoundException("用户名不能为空");
        }
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        User user = userService.getOne(wrapper);// 用户名必须唯一
        if (user == null) {
            throw new UsernameNotFoundException("数据库中未找到用户名为" + username + "的用户");
        }
        // 角色
//        List<GrantedAuthority> list = new ArrayList<>();
        List<Role> roles = roleMapper.findRolesByUserId(user.getId());
//        user.setRoles(roles);
//        for (Role role : roles) {
//            /*授予角色*/
//            list.add(new SimpleGrantedAuthority(role.getCode()));
//            /*Set<Permission> permissions = role.getPermissions();
//            for (Permission permission : permissions) {
//                //授予权限
//                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
//            }*/
//        }
        // 给SecurityUser赋值
        SecurityUser securityUser = new SecurityUser(user);
        securityUser.setRoles(roles);
        return securityUser;
    }
}
